﻿using System;
using System.IO;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections.Generic;

namespace JPG转换器
{
    public partial class Form1 : Form
    {
        #region 定义进度变量和转换列表变量
        private int _currentProgress;
        private readonly List<string> _i = new List<string>();
        #endregion

        public Form1()
        {
            InitializeComponent();
        }

        private void Add_Folder_Button_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK != AddFolderDialog.ShowDialog()) return;    //当未选择文件夹时调用return关键字直接跳出方法；
            #region 初始化转换列表
            _i.Clear();
            progressBar1.Value = 0;
            _currentProgress = 0;
            #endregion
            AddItems(textBox1.Text = AddFolderDialog.SelectedPath);
            if (_i.Count == 0)
            {
                MessageBox.Show(@"未找到合适的文件");
            }
        }

        private void Convert_Button_Click(object sender, EventArgs e)
        {
            switch (_i.Count)
            {
                case 0:
                    MessageBox.Show(@"未找到合适的文件");
                    break;
                default:
                    if (backgroundWorker1.IsBusy)
                    {
                        backgroundWorker1.CancelAsync();
                    }
                    else
                    {
                        #region 转换时禁用控件                        
                        Add_Folder_Button.Enabled = false;
                        checkBox1.Enabled = false;
                        checkBox2.Enabled = false;
                        #endregion
                        Convert_Button.Text = @"取消";
                        progressBar1.Maximum = _i.Count;
                        backgroundWorker1.RunWorkerAsync(progressBar1.Maximum);
                    }
                    break;
            }
        }

        private void AddItems(string path)      //调用递归算法遍历文件树
        {
            _i.AddRange(Directory.GetFiles(path, "*.png"));
            _i.AddRange(Directory.GetFiles(path, "*.bmp"));
            foreach (var item in Directory.GetDirectories(path))
            {
                AddItems(item);          
            }
        }

        private static string ChangeExtension(string path) => Path.ChangeExtension(path, ".jpg");

        private void Convert2Jpg(string path)
        {
            if (!File.Exists(path)) return;             //文件不存在时直接调用return跳出方法                                
            if (File.Exists(ChangeExtension(path)))
            {
                if (!checkBox2.Checked)
                {
                    if (!checkBox1.Checked) return;     
                    File.SetAttributes(path, FileAttributes.Normal);    //设置文件属性为普通
                    File.Delete(path);
                    return;                                                         
                }
                else
                {
                    File.Delete(ChangeExtension(path));
                }
            }
            #region 转换图片为JPG格式具体实现代码
            var img = Image.FromFile(path);
            img.Save(ChangeExtension(path), ImageFormat.Jpeg);
            img.Dispose();
            #endregion
            if (!checkBox1.Checked) return;
            File.SetAttributes(path, FileAttributes.Normal);
            File.Delete(path);
        }

        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            #region 当转换完毕后再次转换时重置进度
            if (progressBar1.Value == progressBar1.Maximum)
            {
                _currentProgress = 0; 
            }
            #endregion
            for (; _currentProgress < _i.Count;)
            {
                if (backgroundWorker1.CancellationPending) return;
                Convert2Jpg(_i[_currentProgress]);
                backgroundWorker1.ReportProgress(++_currentProgress);
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            #region 转换结束后重新启用控件
            Add_Folder_Button.Enabled = true;
            checkBox1.Enabled = true;
            checkBox2.Enabled = true;
            #endregion
            Convert_Button.Text = @"转换";
            MessageBox.Show(progressBar1.Value < progressBar1.Maximum ? "操作被用户取消！" : "转换完毕！");    //通过三目运算符简化逻辑判断
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            backgroundWorker1.CancelAsync();
        }
    }
}